<?php
require_once __DIR__ . '/../models/Topic.php';

class TopicController
{
	private $db;
	private $topicModel;

	public function __construct($db)
	{
		$this->db = $db;
		$this->topicModel = new Topic($db);
	}

	//	获取最新讨论
	public function getLatestTopics()
	{
		try {
			// 从查询参数获取limit值，默认10
			$limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 10;

			$topics = $this->topicModel->getLatestTopics($limit);

			if (empty($topics)) {
				http_response_code(404);
				echo json_encode(['message' => 'No topics found']);
				return;
			}

			// 格式化日期等字段
			$formattedTopics = array_map(function ($topic) {
				return [
					'id' => $topic['topic_id'],
					'title' => $topic['title'],
					'content' => $topic['content'],
					'view_count' => $topic['view_count'],
					'like_count' => $topic['like_count'],
					'reply_count' => $topic['reply_count'],
					'created_at' => $topic['created_at'],
					'category_id' => $topic['category_id'] ?? null,
					'user' => [
						'id' => $topic['user_id'],
						'username' => $topic['username'],
						'avatar_url' => $topic['avatar_url']
					]
				];
			}, $topics);

			http_response_code(200);
			echo json_encode([
				'status' => 'success',
				'count' => count($formattedTopics),
				'data' => $formattedTopics
			]);

		} catch (Exception $e) {
			http_response_code(500);
			echo json_encode([
				'status' => 'error',
				'message' => $e->getMessage()
			]);
		}
	}

	// 获取指定分类下的讨论
	public function getTopicsByCategory()
	{
		try {
			// 从查询参数获取category_id
			$categoryId = $_GET['category_id'] ?? null;

			if (!$categoryId) {
				http_response_code(400);
				echo json_encode(['error' => 'category_id parameter is required']);
				return;
			}

			$topics = $this->topicModel->getTopicsByCategory($categoryId);

			if (empty($topics)) {
				http_response_code(404);
				echo json_encode(['message' => 'No topics found in this category']);
				return;
			}

			// 格式化响应数据
			$formattedTopics = array_map(function ($topic) {
				return [
					'topic_id' => $topic['topic_id'] ?? null,
					'title' => $topic['title'] ?? '',
					'content' => $topic['content'] ?? '',
					'view_count' => $topic['view_count'] ?? 0,
					'like_count' => $topic['like_count'],
					'reply_count' => $topic['reply_count'],
					'created_at' => $topic['created_at'] ?? null,
					'category_id' => $topic['category_id'] ?? null,
					'user' => [
						'id' => $topic['user_id'] ?? null,
						'username' => $topic['username'] ?? '',
						'avatar_url' => $topic['avatar_url'] ?? ''
					]
				];
			}, $topics);

			http_response_code(200);
			echo json_encode([
				'status' => 'success',
				'category_id' => (int) $categoryId,
				'count' => count($formattedTopics),
				'data' => $formattedTopics
			]);

		} catch (Exception $e) {
			http_response_code(500);
			echo json_encode([
				'status' => 'error',
				'message' => $e->getMessage()
			]);
		}
	}

	// 发帖
	public function releaseTopic(): void
	{
		try {
			$data = json_decode(file_get_contents('php://input'), true);

			// 基本数据验证
			if (
				empty($data['user_id']) || empty($data['category_id']) ||
				empty($data['title']) || empty($data['content'])
			) {
				throw new Exception('Missing required fields');
			}

			$topicId = $this->topicModel->insertTopic(
				$data['user_id'],
				$data['category_id'],
				$data['title'],
				$data['content'],
				$data['is_pinned'] ?? 0,
				$data['is_closed'] ?? 0
			);

			$newTopic = $this->topicModel->getTopicById($topicId);

			http_response_code(201);
			echo json_encode([
				'status' => 'success',
				'message' => 'Topic released successfully',
				'data' => $newTopic
			]);

		} catch (Exception $e) {
			http_response_code(400);
			echo json_encode([
				'status' => 'error',
				'message' => $e->getMessage()
			]);
		}
	}
}
?>